package com.quasar.hpatient.module.comm_qrcode;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.Result;
import com.quasar.hpatient.R;
import com.quasar.hpatient.bean.comm_album.AlbumPhotoBean;
import com.quasar.hpatient.module.comm_album.AlbumActivity;
import com.quasar.hpatient.module.comm_card.CardActivity;

import java.util.ArrayList;
import java.util.Collection;

import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import lib.quasar.base.frame.BaseActivity;
import lib.quasar.qrcode.ZXingUtil;
import lib.quasar.qrcode.ZxingManager;
import lib.quasar.qrcode.camera.CameraManager;
import lib.quasar.qrcode.hanlder.CaptureActivityHandler;
import lib.quasar.qrcode.manager.BeepManager;
import lib.quasar.qrcode.manager.InactivityTimer;
import lib.quasar.qrcode.widget.QrcodeView;
import lib.quasar.util.BitmapUtil;
import lib.quasar.util.LogUtil;

/**
 * description: 二维码扫描
 * created by kalu on 2018/7/5 9:07
 */
public final class QrcodeActivity extends BaseActivity<QrcodePresenter> implements com.quasar.hpatient.module.comm_qrcode.QrcodeView, SurfaceHolder.Callback {

    public static final int REQUEST_CODE = 1001;
    public static final String INTENT_KEY_NAME = "INTENT_KEY_NAME";

    //常量
    public static final int RESULT_SUCCESS = 0;
    public static final int RESULT_FAIL = 1;
    public static final int RESULT_CANCLE = 2;
    private static final String TAG = QrcodeActivity.class.getSimpleName();
    private CameraManager cameraManager;
    private CaptureActivityHandler handler;
    private QrcodeView viewfinderView;
    private boolean hasSurface;
    private Collection<BarcodeFormat> decodeFormats;
    private String characterSet;
    private InactivityTimer inactivityTimer;
    private BeepManager beepManager;

    private LinearLayout btn_scan_light;
    private ImageView iv_scan_light;
    private TextView tv_scan_light;
    //闪光灯是否打开
    private boolean is_light_on = false;
    private boolean beepFlag = true;
    private boolean vibrateFlag = true;
    private SurfaceView surfaceView;

    public Handler getHandler() {
        return handler;
    }

    public CameraManager getCameraManager() {
        return cameraManager;
    }

    @Override
    public int initView() {
        Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        return R.layout.activity_comm_qrcode;
    }

    @Override
    public void initDataNet() {
    }

    @Override
    public void initDataLocal() {

        surfaceView = findViewById(R.id.preview_view);
        viewfinderView = findViewById(R.id.viewfinder_view);
        btn_scan_light = findViewById(R.id.btn_scan_light);
        iv_scan_light = findViewById(R.id.iv_scan_light);
        tv_scan_light = findViewById(R.id.tv_scan_light);

        //初始化相关参数
        Intent intent = getIntent();
        String hintText = intent.getStringExtra(ZxingManager.INTENT_KEY_HINTTEXT);
        int scanColor = intent.getIntExtra(ZxingManager.INTENT_KEY_SCSNCOLOR, Color.GREEN);
        boolean photoFlag = intent.getBooleanExtra(ZxingManager.INTENT_KEY_PHOTO_FLAG, true);
        beepFlag = intent.getBooleanExtra(ZxingManager.INTENT_KEY_BEEP_FLAG, true);
        vibrateFlag = intent.getBooleanExtra(ZxingManager.INTENT_KEY_VIBRATE_FLAG, true);
        if (!TextUtils.isEmpty(hintText)) {
            viewfinderView.setHintText(hintText);
        }
        viewfinderView.setScanLineColor(scanColor);
        if (!photoFlag) {
            findViewById(R.id.btn_photo).setVisibility(View.GONE);
        }

        hasSurface = false;
        inactivityTimer = new InactivityTimer(this);
        beepManager = new BeepManager(this);

        //点击事件
        btn_scan_light.setOnClickListener(v -> {
            if (is_light_on) {
                cameraManager.offLight();
            } else {
                cameraManager.openLight();
            }
            iv_scan_light.setImageResource(is_light_on ? R.drawable.ic_comm_light_off : R.drawable.ic_comm_light_on);
            tv_scan_light.setText(is_light_on ? R.string.comm_qrcode_light_off : R.string.comm_qrcode_light_on);
            tv_scan_light.setTextColor(getResources().getColor(is_light_on ? R.color.color_white : R.color.color_bg_theme));
            is_light_on = !is_light_on;
        });

        findViewById(R.id.btn_close).setOnClickListener(v -> finishCancle());

        findViewById(R.id.btn_photo).setOnClickListener(v -> {

            //  LogUtil.e("qrcode", "打开相册");
            Intent intent1 = new Intent(getApplicationContext(), AlbumActivity.class);
            startActivityForResult(intent1, REQUEST_CODE);
        });

        findViewById(R.id.activity_comm_qrcode_card).setOnClickListener(view -> {
            Intent intent1 = new Intent(getApplicationContext(), CardActivity.class);
            startActivity(intent1);
        });
    }

    @SuppressLint("CheckResult")
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //     LogUtil.e("qrcode", "requestCode = " + requestCode + ", resultCode = " + resultCode);

        if (requestCode != REQUEST_CODE || resultCode != AlbumActivity.RESULT_CODE || null == data)
            return;

        final ArrayList<AlbumPhotoBean> list = data.getParcelableArrayListExtra(AlbumActivity.LIST);
        //   LogUtil.e("qrcode", "返回相册, " + list.get(0).getCover());
        if (null == list || list.size() == 0) return;

        Observable.create((ObservableOnSubscribe<String>) e -> {

            final Bitmap bitmap = BitmapUtil.decodeBitmap(list.get(0).getPicture());
            final String info = ZXingUtil.syncDecodeQRCode(bitmap);
            bitmap.recycle();
            e.onNext(info);
        }).subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(info -> {

//                            Intent intent = new Intent();
//                            intent.putExtra(INTENT_KEY_NAME, info);
//                            setResult(RESULT_SUCCESS, intent);
//                            onBackPressed();
                            toast(info);

                        }, throwable -> toast("分线程: 识别图片失败"),
                        () -> toast("分线程: 识别图片结束"),
                        disposable -> toast("分线程: 识别图片开始"));
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (handler != null && cameraManager != null && cameraManager.isOpen()) {
            return;
        }
        cameraManager = new CameraManager(getApplication());
        viewfinderView.setCameraManager(cameraManager);

        handler = null;

        resetStatusView();

        beepManager.updatePrefs(beepFlag, vibrateFlag);

        inactivityTimer.onResume();
        decodeFormats = null;
        characterSet = null;

        SurfaceHolder surfaceHolder = surfaceView.getHolder();
        if (hasSurface) {
            // 防止sdk8的设备初始化预览异常
            surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
            // The activity was paused but not stopped, so the surface still exists. Therefore
            // surfaceCreated() won't be called, so init the camera here.
            initCamera(surfaceHolder);
        } else {
            // Install the callback and wait for surfaceCreated() to init the camera.
            surfaceHolder.addCallback(this);
        }
    }

    @Override
    protected void onPause() {
        if (handler != null) {
            handler.quitSynchronously();
            handler = null;
        }
        inactivityTimer.onPause();
        beepManager.close();
        cameraManager.closeDriver();
        //historyManager = null; // Keep for onActivityResult
        if (!hasSurface) {
            SurfaceHolder surfaceHolder = surfaceView.getHolder();
            surfaceHolder.removeCallback(this);
        }
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        inactivityTimer.shutdown();
        super.onDestroy();
    }

    @Override
    public void onBackPressed() {
        //取消扫码
        finishCancle();
    }

    public void handleDecode(Result result, Bitmap bitmap, float scaleFactor) {
        LogUtil.e("qrcode", "handleDecode, " + result.getText());

        if (null != bitmap) {
            bitmap.recycle();
        }

        //播放声音和震动
        beepManager.playBeepSoundAndVibrate();
        //关闭页面
        onBackPressed();
    }

    private void finishFailed(String errorMsg) {
        toast("finishFailed ==> "+errorMsg);
//        Intent intent = new Intent();
//        intent.putExtra(ZxingManager.INTENT_KEY_RESULT_ERROR, errorMsg);
//        this.setResult(RESULT_FAIL, intent);
//        this.finish();
    }

    private void finishCancle() {
        toast("finishCancle ==> "        );
//        this.setResult(RESULT_CANCLE, null);
//        this.finish();
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        if (holder == null) {
            Log.e(TAG, "*** WARNING *** surfaceCreated() gave us a null surface!");
        }
        if (!hasSurface) {
            hasSurface = true;
            initCamera(holder);
        }
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        hasSurface = false;
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        // do nothing
    }

    private void initCamera(SurfaceHolder surfaceHolder) {
        if (surfaceHolder == null) {
            displayFrameworkBugMessageAndExit("SurfaceHolder 不存在");
        }
        if (cameraManager.isOpen()) {
            Log.w(TAG, "initCamera() while already open -- late SurfaceView callback?");
            return;
        }
        try {
            cameraManager.openDriver(surfaceHolder);
            // Creating the handler starts the preview, which can also throw a RuntimeException.
            if (handler == null) {
                handler = new CaptureActivityHandler(this, decodeFormats, null, characterSet, cameraManager);
            }
        } catch (Exception e) {
            displayFrameworkBugMessageAndExit("开启摄像头异常：" + e.toString());
        }
    }

    private void displayFrameworkBugMessageAndExit(String errorMessage) {
        finishFailed(errorMessage);
    }

    public void restartPreviewAfterDelay(long delayMS) {
        if (handler != null) {
            handler.sendEmptyMessageDelayed(R.id.restart_preview, delayMS);
        }
        resetStatusView();
    }

    private void resetStatusView() {
        viewfinderView.setVisibility(View.VISIBLE);
    }

    public void drawViewfinder() {
        viewfinderView.drawViewfinder();
    }
}
